<!DOCTYPE html>
<html lang="zh-Hans">
<meta name="theme-color" content="#FFFFFF">


<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=no">
  <meta name="theme-color" content="#202020"/>
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  <link rel="shortcut icon" href="/images/favicon.ico" type="image/x-icon" />
  <link rel="icon" sizes="any" mask href="/images/favicon.ico" /> 
  
  

  <!-- viewjs support -->
  
    <!-- for theme: default is false -->
    <!-- for page: default is true -->
    <link  href="./css/viewer.min.css" rel="stylesheet" >
    <script src="./js/viewer.min.js" type="text/javascript" charset="utf-8"></script>
  
  
  
    <meta name="keywords" content="Java,tech," />
  

  
    <meta name="description" content="分享 Java 技术，做有趣的程序员" />
  
  
  <link rel="icon" type="image/x-icon" href="/logo.png">
  <title>Java压缩流GZIPStream导致的内存泄露 [ H E R O ]</title>
  
    <!-- stylesheets list from config.yml -->
    
      <link rel="stylesheet" href="//cdn.bootcss.com/pure/1.0.0/pure-min.css">
    
      <link rel="stylesheet" href="/css/xoxo.css">
    
  
<meta name="generator" content="Hexo 5.4.0"></head>


<body>
  <div class="nav-container">
    <nav id="menu" class="home-menu pure-menu pure-menu-horizontal">
  <a class="pure-menu-heading" href="/">
    <!-- <img class="avatar" src="/images/logo.png"> -->
    <span class="title">H E R O</span>
  </a>

  <ul class="pure-menu-list clearfix">
      
          
            <li class="pure-menu-item"><a href="/" class="pure-menu-link">首页</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/archives/" class="pure-menu-link">归档</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/tags/" class="pure-menu-link">标签</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/about/" class="pure-menu-link">关于</a></li>
          
      
          
            <li class="pure-menu-item"><a href="/atom.xml" class="pure-menu-link">订阅</a></li>
          
      
  </ul>
   
</nav>
  </div>

  <div class="container" id="content-outer">
    <div class="inner" id="content-inner">
      <div class="post-container">
  <article class="post" id="post">
    <header class="post-header text-center">
      <h1 class="title">
        Java压缩流GZIPStream导致的内存泄露
      </h1>
      <span>
        
        <time class="time" datetime="2017-11-16T09:51:20.000Z">
          2017-11-16
        </time>
        
      </span>
      <span class="slash">/</span>
      <span class="post-meta">
        <span class="post-tags">
          <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Java/" rel="tag">Java</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/tech/" rel="tag">tech</a></li></ul>
        </span>
      </span>
      
     
    </header>

    <div class="post-content">
      <p>我们来聊聊<code>GZIPOutputStream</code> 和 <code>GZIPInputStream</code>, 如果不关闭流会引起的内存泄露问题，以及<code>GZIPStream</code>申请和释放堆外内存的流程， Let’s do it!<br><span id="more"></span></p>
<h3 id="引子"><a href="#引子" class="headerlink" title="引子"></a>引子</h3><p>在我的工程里面又一个工具类 <code>ZipHelper</code> 用来压缩和解压 <code>String</code></p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.ByteArrayInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.ByteArrayOutputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.zip.GZIPInputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.zip.GZIPOutputStream;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* 用来压缩和解压字符串</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ZipHelper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 压缩</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">compress</span><span class="params">(String str)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (str == <span class="keyword">null</span> || str.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> str;</span><br><span class="line">        &#125;</span><br><span class="line">        ByteArrayOutputStream out = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">        GZIPOutputStream gzip = <span class="keyword">new</span> GZIPOutputStream(out);</span><br><span class="line">        gzip.write(str.getBytes());</span><br><span class="line">        gzip.close();</span><br><span class="line">        <span class="keyword">return</span> out.toString(<span class="string">&quot;ISO-8859-1&quot;</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 解压缩</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">uncompress</span><span class="params">(String str)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (str == <span class="keyword">null</span> || str.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> str;</span><br><span class="line">        &#125;</span><br><span class="line">        ByteArrayOutputStream out = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">        ByteArrayInputStream in = <span class="keyword">new</span> ByteArrayInputStream(str.getBytes(<span class="string">&quot;ISO-8859-1&quot;</span>));</span><br><span class="line">        GZIPInputStream gunzip = <span class="keyword">new</span> GZIPInputStream(in);</span><br><span class="line">        <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">        <span class="keyword">int</span> n;</span><br><span class="line">        <span class="keyword">while</span> ((n = gunzip.read(buffer)) &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">            out.write(buffer, <span class="number">0</span>, n);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> out.toString();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>最近服务出现了占用swap空间的问题，初步定位为内存泄漏，最后通过分析定位到是 Native 方法<code>Java_java_util_zip_Inflater_init</code>一直在申请内存（关于分析方法可以查阅这篇博客<a href="https://jacobchang.cn/action-in-memory-leak-analysis.html">内存泄露分析实战</a>）但是没有释放，很有可能就是流没有关闭造成的，而这部分代码最大的问题就是没有在<code>finally</code>里面去关闭流，于是乎我打算改造这部分代码，利用 try-with-resource 语法糖，然后代码就被修改成了这样：</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">import</span> java.io.ByteArrayInputStream;</span><br><span class="line"><span class="keyword">import</span> java.io.ByteArrayOutputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.zip.GZIPInputStream;</span><br><span class="line"><span class="keyword">import</span> java.util.zip.GZIPOutputStream;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Created by jacob.</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 用来压缩和解压字符串</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ZipHelper</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 压缩字符串</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> str 待压缩的字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 压缩后的字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception 压缩过程中的异常</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">compress</span><span class="params">(String str)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (str == <span class="keyword">null</span> || str.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> str;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// ByteArrayOutputStream 和 ByteArrayInputStream 是一个虚拟的流,</span></span><br><span class="line">        <span class="comment">// JDk源码中关闭方法是空的, 所以无需关闭, 为了代码整洁，还是放到了try-with-resource里面</span></span><br><span class="line">        <span class="keyword">try</span> (ByteArrayOutputStream out = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">             GZIPOutputStream gzip = <span class="keyword">new</span> GZIPOutputStream(out)) &#123;</span><br><span class="line">            gzip.write(str.getBytes());</span><br><span class="line"><span class="comment">//            gzip.finish();</span></span><br><span class="line">            <span class="keyword">return</span> out.toString(<span class="string">&quot;ISO-8859-1&quot;</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 解压字符串</span></span><br><span class="line"><span class="comment">     *</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> str 待解压的字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> 解压后的字符串</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception 解压过程中的异常</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> String <span class="title">uncompress</span><span class="params">(String str)</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (str == <span class="keyword">null</span> || str.length() == <span class="number">0</span>) &#123;</span><br><span class="line">            <span class="keyword">return</span> str;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> (ByteArrayOutputStream out = <span class="keyword">new</span> ByteArrayOutputStream();</span><br><span class="line">             ByteArrayInputStream in = <span class="keyword">new</span> ByteArrayInputStream(str.getBytes(<span class="string">&quot;ISO-8859-1&quot;</span>));</span><br><span class="line">             GZIPInputStream gunzip = <span class="keyword">new</span> GZIPInputStream(in)) &#123;</span><br><span class="line">            <span class="keyword">byte</span>[] buffer = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span>];</span><br><span class="line">            <span class="keyword">int</span> n;</span><br><span class="line">            <span class="keyword">while</span> ((n = gunzip.read(buffer)) &gt;= <span class="number">0</span>) &#123;</span><br><span class="line">                out.write(buffer, <span class="number">0</span>, n);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> out.toString();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>是不是顺眼多了呐，可是这样的代码可以压缩的，在解压的时候会报错。一开始我以为是解压的代码出现了问题，最后才发现是因为压缩的时候没有成功压缩，导致解压的时候无法解压。报以下错误</p>
<figure class="highlight plain"><table><tr><td class="code"><pre><span class="line">Exception in thread &quot;main&quot; java.io.EOFException: Unexpected end of ZLIB input stream</span><br><span class="line">	at java.util.zip.InflaterInputStream.fill(InflaterInputStream.java:240)</span><br><span class="line">	at java.util.zip.InflaterInputStream.read(InflaterInputStream.java:158)</span><br><span class="line">	at java.util.zip.GZIPInputStream.read(GZIPInputStream.java:117)</span><br><span class="line">	at java.io.FilterInputStream.read(FilterInputStream.java:107)</span><br><span class="line">	at coderbean.ZipHelper.uncompress(ZipHelper.java:52)</span><br><span class="line">	at coderbean.Main.main(Main.java:12)</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>好好的代码怎么会突然压缩失败，后来发现的问题是在<code>GZIPOutputStream</code>中，在<code>close()</code>方法中会主动调用<code>finish()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">* Writes remaining compressed data to the output stream and closes the</span></span><br><span class="line"><span class="comment">* underlying stream.</span></span><br><span class="line"><span class="comment">* <span class="doctag">@exception</span> IOException if an I/O error has occurred</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">   <span class="keyword">if</span> (!closed) &#123;</span><br><span class="line">       finish();</span><br><span class="line">       <span class="keyword">if</span> (usesDefaultDeflater)</span><br><span class="line">           def.end();</span><br><span class="line">       out.close();</span><br><span class="line">       closed = <span class="keyword">true</span>;</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在下面的方法中才会将压缩后的数据输出到输入流，由于原来的代码会调用 <code>close()</code>方法，从而间接调用了 <code>finish()</code> 方法。那我我们的<code>try-with-resource</code>到底出了什么问题，其实问题就在于执行<code>close()</code>的时间。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Finishes writing compressed data to the output stream without closing</span></span><br><span class="line"><span class="comment"> * the underlying stream. Use this method when applying multiple filters</span></span><br><span class="line"><span class="comment"> * in succession to the same output stream.</span></span><br><span class="line"><span class="comment"> * 在该方法中才会将压缩后的数据输出到输入流，由于原来的代码会调用 close()方法，从而</span></span><br><span class="line"><span class="comment"> * 间接调用了 finish() 方法。</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@exception</span> IOException if an I/O error has occurred</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">finish</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!def.finished()) &#123;</span><br><span class="line">        def.finish();</span><br><span class="line">        <span class="keyword">while</span> (!def.finished()) &#123;</span><br><span class="line">            <span class="keyword">int</span> len = def.deflate(buf, <span class="number">0</span>, buf.length);</span><br><span class="line">            <span class="keyword">if</span> (def.finished() &amp;&amp; len &lt;= buf.length - TRAILER_SIZE) &#123;</span><br><span class="line">                <span class="comment">// last deflater buffer. Fit trailer at the end</span></span><br><span class="line">                writeTrailer(buf, len);</span><br><span class="line">                len = len + TRAILER_SIZE;</span><br><span class="line">                out.write(buf, <span class="number">0</span>, len);</span><br><span class="line">                <span class="keyword">return</span>;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">if</span> (len &gt; <span class="number">0</span>)</span><br><span class="line">                out.write(buf, <span class="number">0</span>, len);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// if we can&#x27;t fit the trailer at the end of the last</span></span><br><span class="line">        <span class="comment">// deflater buffer, we write it separately</span></span><br><span class="line">        <span class="keyword">byte</span>[] trailer = <span class="keyword">new</span> <span class="keyword">byte</span>[TRAILER_SIZE];</span><br><span class="line">        writeTrailer(trailer, <span class="number">0</span>);</span><br><span class="line">        out.write(trailer);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="try-with-resource-执行时机和条件"><a href="#try-with-resource-执行时机和条件" class="headerlink" title="try-with-resource 执行时机和条件"></a><code>try-with-resource</code> 执行时机和条件</h3><p><code>try-with-resource</code> 是在 JDK7 中新增加的语法糖（其实就是抄的C#），用来自动执行流的关闭操作，只要该类实现了<code>AutoCloseable</code>的<code>close()</code>方法。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">package</span> java.lang;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">AutoCloseable</span> </span>&#123;</span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception if this resource cannot be closed</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<p>实现了这个接口之后，我们可以将会在<code>try</code>代码块执行结束之后自动关闭流</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="keyword">try</span>(<span class="comment">/* 在此处初始化资源 */</span>)&#123;</span><br><span class="line">  <span class="comment">// do something</span></span><br><span class="line">&#125; <span class="comment">//在代码块执行结束前最后一步关闭流</span></span><br></pre></td></tr></table></figure>
<p>由于在<code>GZIPOutputStream</code>执行了<code>finish()</code>方法或者<code>close()</code>方法之后才会真正的将压缩后的数据写入流，在上文我改造的代码中并没有首先执行<code>finish()</code>方法，而是直接在<code>try</code>代码块执行完之后关闭了流 <code>GZIPOutputStream</code>, 由于<code>close()</code>方法执行在<code>out.toString(&quot;ISO-8859-1&quot;)</code>之后，因此压缩并没有真正的被执行，然而对于<code>ZipHelper.compress()</code>方法并没有感知，而是返回了没有压缩成功的字符串，从而造成在解压的时候报错。</p>
<h3 id="为什么会引起的堆外内存泄漏"><a href="#为什么会引起的堆外内存泄漏" class="headerlink" title="为什么会引起的堆外内存泄漏"></a>为什么会引起的堆外内存泄漏</h3><p>通过最开始的代码我们可以看出，在没有发生异常的情况下，<code>compress()</code>方法是可以正常的关闭流的，所以内存泄露的根源应该是在<code>uncompress()</code>方法，通过跟踪<code>GZIPInputStream</code>的构造函数和<code>close()</code>应该很快就能找到答案。</p>
<p>下面是申请堆外内存和释放堆外内存的过程调用图，可以对比代码参考<br><img src="https://image-hosting-1251780645.cos.ap-beijing.myqcloud.com/fromSina/006tKfTcly1flnrogyecdj316u0mudiq.jpg" alt="堆外内存调用释放流程图"></p>
<p>由于篇幅的原因就不将JDK源码注释一同贴上来了，感兴趣的同学可以按图索骥，找到对应的注释。</p>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//java.util.zip.GZIPInputStream.java</span></span><br><span class="line"><span class="keyword">public</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">GZIPInputStream</span> <span class="keyword">extends</span> <span class="title">InflaterInputStream</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GZIPInputStream</span><span class="params">(InputStream in)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">this</span>(in, <span class="number">512</span>); <span class="comment">//调用下面的构造函数</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">GZIPInputStream</span><span class="params">(InputStream in, <span class="keyword">int</span> size)</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>(in, <span class="keyword">new</span> Inflater(<span class="keyword">true</span>), size); <span class="comment">//新建 Inflater 对象</span></span><br><span class="line">        usesDefaultInflater = <span class="keyword">true</span>;</span><br><span class="line">        readHeader(in);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!closed) &#123;</span><br><span class="line">            <span class="keyword">super</span>.close(); <span class="comment">//这里的父类是java.util.zip.InflaterInputStream</span></span><br><span class="line">            eos = <span class="keyword">true</span>;</span><br><span class="line">            closed = <span class="keyword">true</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//java.util.zip.Inflater.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Inflater</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="title">Inflater</span><span class="params">(<span class="keyword">boolean</span> nowrap)</span> </span>&#123;</span><br><span class="line">        zsRef = <span class="keyword">new</span> ZStreamRef(init(nowrap));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Closes the decompressor and discards any unprocessed input.</span></span><br><span class="line"><span class="comment">     * This method should be called when the decompressor is no longer</span></span><br><span class="line"><span class="comment">     * being used, but will also be called automatically by the finalize()</span></span><br><span class="line"><span class="comment">     * method. Once this method is called, the behavior of the Inflater</span></span><br><span class="line"><span class="comment">     * object is undefined.</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">end</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (zsRef) &#123;</span><br><span class="line">            <span class="keyword">long</span> addr = zsRef.address();</span><br><span class="line">            zsRef.clear();</span><br><span class="line">            <span class="keyword">if</span> (addr != <span class="number">0</span>) &#123;</span><br><span class="line">                end(addr);</span><br><span class="line">                buf = <span class="keyword">null</span>;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 此处调用了 Native 方法</span></span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">native</span> <span class="keyword">static</span> <span class="keyword">long</span> <span class="title">init</span><span class="params">(<span class="keyword">boolean</span> nowrap)</span></span>;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">native</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">end</span><span class="params">(<span class="keyword">long</span> addr)</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line"><span class="comment">//java.util.zip.InflaterInputStream.java</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">InflaterInputStream</span> <span class="keyword">extends</span> <span class="title">FilterInputStream</span> </span>&#123;</span><br><span class="line">  <span class="comment">/**</span></span><br><span class="line"><span class="comment">   * Closes this input stream and releases any system resources associated</span></span><br><span class="line"><span class="comment">   * with the stream.</span></span><br><span class="line"><span class="comment">   * <span class="doctag">@exception</span> IOException if an I/O error has occurred</span></span><br><span class="line"><span class="comment">   */</span></span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">close</span><span class="params">()</span> <span class="keyword">throws</span> IOException </span>&#123;</span><br><span class="line">      <span class="keyword">if</span> (!closed) &#123;</span><br><span class="line">          <span class="keyword">if</span> (usesDefaultInflater)</span><br><span class="line">              inf.end();</span><br><span class="line">          in.close();</span><br><span class="line">          closed = <span class="keyword">true</span>;</span><br><span class="line">      &#125;</span><br><span class="line">  &#125;  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>openJDK 中 JVM 关于这个本地方法的实现</p>
<figure class="highlight cpp"><table><tr><td class="code"><pre><span class="line">JNIEXPORT jlong JNICALL</span><br><span class="line"><span class="built_in">Java_java_util_zip_Inflater_init</span>(JNIEnv *env, jclass cls, jboolean nowrap)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//此处使用 calloc 申请了堆外内存</span></span><br><span class="line">    z_stream *strm = <span class="built_in">calloc</span>(<span class="number">1</span>, <span class="built_in"><span class="keyword">sizeof</span></span>(z_stream));</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (strm == <span class="literal">NULL</span>) &#123;</span><br><span class="line">        <span class="built_in">JNU_ThrowOutOfMemoryError</span>(env, <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">return</span> jlong_zero;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> <span class="keyword">char</span> *msg;</span><br><span class="line">        <span class="keyword">int</span> ret = <span class="built_in">inflateInit2</span>(strm, nowrap ? -MAX_WBITS : MAX_WBITS);</span><br><span class="line">        <span class="built_in"><span class="keyword">switch</span></span> (ret) &#123;</span><br><span class="line">          <span class="keyword">case</span> Z_OK:</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">ptr_to_jlong</span>(strm);</span><br><span class="line">          <span class="keyword">case</span> Z_MEM_ERROR:</span><br><span class="line">            <span class="built_in">free</span>(strm);</span><br><span class="line">            <span class="built_in">JNU_ThrowOutOfMemoryError</span>(env, <span class="number">0</span>);</span><br><span class="line">            <span class="keyword">return</span> jlong_zero;</span><br><span class="line">          <span class="keyword">default</span>:</span><br><span class="line">            msg = ((strm-&gt;msg != <span class="literal">NULL</span>) ? strm-&gt;msg :</span><br><span class="line">                   (ret == Z_VERSION_ERROR) ?</span><br><span class="line">                   <span class="string">&quot;zlib returned Z_VERSION_ERROR: &quot;</span></span><br><span class="line">                   <span class="string">&quot;compile time and runtime zlib implementations differ&quot;</span> :</span><br><span class="line">                   (ret == Z_STREAM_ERROR) ?</span><br><span class="line">                   <span class="string">&quot;inflateInit2 returned Z_STREAM_ERROR&quot;</span> :</span><br><span class="line">                   <span class="string">&quot;unknown error initializing zlib library&quot;</span>);</span><br><span class="line">            <span class="built_in">free</span>(strm);</span><br><span class="line">            <span class="built_in">JNU_ThrowInternalError</span>(env, msg);</span><br><span class="line">            <span class="keyword">return</span> jlong_zero;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">JNIEXPORT <span class="keyword">void</span> JNICALL</span><br><span class="line"><span class="built_in">Java_java_util_zip_Inflater_end</span>(JNIEnv *env, jclass cls, jlong addr)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">inflateEnd</span>(<span class="built_in">jlong_to_ptr</span>(addr)) == Z_STREAM_ERROR) &#123;</span><br><span class="line">        <span class="built_in">JNU_ThrowInternalError</span>(env, <span class="number">0</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="built_in">free</span>(<span class="built_in">jlong_to_ptr</span>(addr)); <span class="comment">//此处释放堆外内存</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h3><ul>
<li><a target="_blank" rel="noopener" href="http://blog.csdn.net/Revivedsun/article/details/52073554">java.io.EOFException: Unexpected end of ZLIB input stream异常处理</a></li>
</ul>

    </div>
    <br>
    <div>全文完。</div>
  </article>
  <div class="toc-container">
    
  <div id="toc" class="toc-article">
    <strong class="toc-title">目录</strong>
    <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%95%E5%AD%90"><span class="toc-text">引子</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#try-with-resource-%E6%89%A7%E8%A1%8C%E6%97%B6%E6%9C%BA%E5%92%8C%E6%9D%A1%E4%BB%B6"><span class="toc-text">try-with-resource 执行时机和条件</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BA%E4%BB%80%E4%B9%88%E4%BC%9A%E5%BC%95%E8%B5%B7%E7%9A%84%E5%A0%86%E5%A4%96%E5%86%85%E5%AD%98%E6%B3%84%E6%BC%8F"><span class="toc-text">为什么会引起的堆外内存泄漏</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E8%80%83"><span class="toc-text">参考</span></a></li></ol>
  </div>


  </div>
</div>
<div class="copyright">
    <span>本作品采用</span>
    <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by/4.0/">知识共享署名 4.0 国际许可协议</a>
    <span>进行许可。 转载时请注明原文链接。</span>
</div>
<div class="share" style="width: 100%;">
  <img src="/images/wechat-qcode.jpg" height="200" width="200" alt="" style="margin: auto; display: block;" />

  <div style="margin: auto; text-align: center; font-size: 0.8em; color: grey;">关注“豆菽技术”公众号</div>
  
</div>

  
    <div class="post-nav">
      <div class="post-nav-item post-nav-next">
        
          <span>〈 </span>
          <a href="/jmm-of-jvm.html" rel="next" title="JVM 探究（一）：JVM内存模型概念模型">
          JVM 探究（一）：JVM内存模型概念模型
          </a>
        
      </div>
  
      <div class="post-nav-item post-nav-prev">
          
          <a href="/experiment-on-jvm.html" rel="prev" title="JVM-探究（二）：JVM实验和 GC 日志解读">
            JVM-探究（二）：JVM实验和 GC 日志解读
          </a>
          <span>〉</span>
        
      </div>
    </div>
  

  <section class="disqus-comments">
    <div id="disqus_thread">
      <noscript>Please enable JavaScript to view the <a target="_blank" rel="noopener" href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
    </div>
  </section>

  <script>
    var disqus_shortname = 'coderbean';
    
    var disqus_url = 'https://jacobchang.cn/things-about-java-gzipstream.html';
    
    (function(){
      var dsq = document.createElement('script');
      dsq.type = 'text/javascript';
      dsq.async = true;
      dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
    })();
  </script>

  <script id="dsq-count-scr" src="//coderbean.disqus.com/count.js" async></script>



    </div>

    

  </div>
  <footer class="footer text-center">
    <div id="bottom-inner">
        <a class="bottom-item-hide" href="https://jacobchang.cn/" target="_blank">主站</a>
        <!-- <a class="bottom-item-hide">·</a> -->
        <!-- <a class="bottom-item-hide" href="" target="_blank">备份站点</a> -->
        <a class="bottom-item-hide">·</a>
        <a class="bottom-item-hide" href="https://github.com/coderbean" target="_blank">GitHub</a>
        <a class="bottom-item-hide">·</a>
        <a class="bottom-item" href="https://hexo.io" target="_blank">Powered by hexo</a>
        <a class="bottom-item">·</a>
        <a class="bottom-item" href="https://github.com/coderbean/hexo-theme-xoxo" target="_blank">Theme xoxo</a>
    </div>
    <div id="bottom-inner">
        <a class="bottom-item-hide" target="_blank" rel="noopener" href="https://beian.miit.gov.cn">备案号：浙ICP备2021033778号-1</a> 
        <a class="bottom-item-hide">·</a>
        <a id="copyright" class="bottom-item"></a>
    </div>
</footer>

<script language="javascript" type="text/javascript">
    var df = new Date();
    var year = df.getFullYear();
    document.getElementById("copyright").innerHTML = "Copyright © 2017 – " + year + " 黄小豆";
</script>
  

<script>
  (function(window, document, undefined) {

    var timer = null;

    function returnTop() {
      cancelAnimationFrame(timer);
      timer = requestAnimationFrame(function fn() {
        var oTop = document.body.scrollTop || document.documentElement.scrollTop;
        if (oTop > 0) {
          document.body.scrollTop = document.documentElement.scrollTop = oTop - 50;
          timer = requestAnimationFrame(fn);
        } else {
          cancelAnimationFrame(timer);
        }
      });
    }

    var hearts = [];
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          setTimeout(callback, 1000 / 60);
        }
    })();
    init();

    function init() {
      css(".heart{z-index:9999;width: 10px;height: 10px;position: fixed;background: #f00;transform: rotate(45deg);-webkit-transform: rotate(45deg);-moz-transform: rotate(45deg);}.heart:after,.heart:before{content: '';width: inherit;height: inherit;background: inherit;border-radius: 50%;-webkit-border-radius: 50%;-moz-border-radius: 50%;position: absolute;}.heart:after{top: -5px;}.heart:before{left: -5px;}");
      attachEvent();
      gameloop();
      addMenuEvent();
    }

    function gameloop() {
      for (var i = 0; i < hearts.length; i++) {
        if (hearts[i].alpha <= 0) {
          document.body.removeChild(hearts[i].el);
          hearts.splice(i, 1);
          continue;
        }
        hearts[i].y--;
        hearts[i].scale += 0.004;
        hearts[i].alpha -= 0.013;
        hearts[i].el.style.cssText = "left:" + hearts[i].x + "px;top:" + hearts[i].y + "px;opacity:" + hearts[i].alpha + ";transform:scale(" + hearts[i].scale + "," + hearts[i].scale + ") rotate(45deg);background:" + hearts[i].color;
      }
      requestAnimationFrame(gameloop);
    }

    /**
     * 设置点击事件
     * 
     * - 回到顶部
     * - 出现爱心
     */
    function attachEvent() {
      var old = typeof window.onclick === "function" && window.onclick;
      var logo = document.getElementById("menu");
      if (logo) {
        logo.onclick = function(event) {
          // returnTop();
          old && old();
          createHeart(event);
        }
      }
      
    }

    function createHeart(event) {
      var d = document.createElement("div");
      d.className = "heart";
      hearts.push({
        el: d,
        x: event.clientX - 5,
        y: event.clientY - 5,
        scale: 1,
        alpha: 1,
        color: randomColor()
      });
      document.body.appendChild(d);
    }

    function css(css) {
      var style = document.createElement("style");
      style.type = "text/css";
      try {
        style.appendChild(document.createTextNode(css));
      } catch (ex) {
        style.styleSheet.cssText = css;
      }
      document.getElementsByTagName('head')[0].appendChild(style);
    }

    function randomColor() {
      // return "rgb(" + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + "," + (~~(Math.random() * 255)) + ")";
      return "#F44336";
    }

    function addMenuEvent() {
      var menu = document.getElementById('menu-main-post');
      if (menu) {
        var toc = document.getElementById('toc');
        if (toc) {
          menu.onclick = function() {
            if (toc) {
              if (toc.style.display == 'block') {
                toc.style.display = 'none';
              } else {
                toc.style.display = 'block';
              }
            }
          };
        } else {
          menu.style.display = 'none';
        }
      }
    }

  })(window, document);
</script>

  


  <script>
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
                  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
              m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      ga('create', 'UA-155080039-1', 'auto');
      ga('send', 'pageview');
  </script>


  
<link rel='stylesheet' href='https://s3-us-west-2.amazonaws.com/s.cdpn.io/1462889/unicons.css'>

<div class="progress-wrap">
    <svg class="progress-circle svg-content" width="100%" height="100%" viewBox="-1 -1 102 102">
        <path d="M50,1 a49,49 0 0,1 0,98 a49,49 0 0,1 0,-98" />
    </svg>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js'></script>
<script>

    (function ($) {
        "use strict";
        $(document).ready(function () {
            "use strict";

            //Scroll back to top

            var progressPath = document.querySelector('.progress-wrap path');
            var pathLength = progressPath.getTotalLength();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'none';
            progressPath.style.strokeDasharray = pathLength + ' ' + pathLength;
            progressPath.style.strokeDashoffset = pathLength;
            progressPath.getBoundingClientRect();
            progressPath.style.transition = progressPath.style.WebkitTransition = 'stroke-dashoffset 10ms linear';
            var updateProgress = function () {
                var scroll = $(window).scrollTop();
                var height = $(document).height() - $(window).height();
                var progress = pathLength - (scroll * pathLength / height);
                progressPath.style.strokeDashoffset = progress;
            }
            updateProgress();
            $(window).scroll(updateProgress);
            var offset = 50;
            var duration = 550;
            jQuery(window).on('scroll', function () {
                if (jQuery(this).scrollTop() > offset) {
                    jQuery('.progress-wrap').addClass('active-progress');
                } else {
                    jQuery('.progress-wrap').removeClass('active-progress');
                }
            });
            jQuery('.progress-wrap').on('click', function (event) {
                event.preventDefault();
                jQuery('html, body').animate({ scrollTop: 0 }, duration);
                return false;
            })


        });

    })(jQuery);
</script>

  
<!-- for theme: default is false -->
<!-- for page: default is true -->
<!-- 图片查看器实例配置 -->
<script type="text/javascript">
    //默认设置， 可以根据个人需求和喜好进行配置
    //详细参考官方说明
    Viewer.setDefaults({
        //设置初始缩放 default: 1
        zoomRatio: [0.5],
        // 过渡动画
        transition:true,
        // 显示工具条
        toolbar: false,
    });
    //获得content中所有的图片， 不同主题可能有所不同
    //为了和其他的图片区别开来 所以在markdown中插入图片的时候使用独特的记号
    //为了一次性得到所有的图片我这里采用的是class = 'article-image'
    var article = document.querySelector('.post-content');
    if(article!=null) {
        var imageList = article.getElementsByTagName('img');
        //将获取到的HTMLCollections转化成Array
        var imageArray = new Array();
        Array.prototype.forEach.call(imageList, element => {
            imageArray.push(element);
        });
        //设置每个图片成为图片组
        Array.prototype.forEach.call(imageList, element => {
            var viewer1 = new Viewer(element);
            viewer1.images = imageArray;
            viewer1.length = imageArray.length;
        });
    }

    
</script>

  
  <! -- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
                processEscapes: true
                    
}
  
        });
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {
            skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
                  
}
    
        });
</script>

<script type="text/x-mathjax-config">
MathJax.Hub.Queue(function() {
            var all = MathJax.Hub.getAllJax(), i;
            for(i=0; i < all.length; i += 1) {
                            all[i].SourceElement().parentNode.className += ' has-jax';
                                    
            }
                
        });
</script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=TeX-MML-AM_CHTML"></script>

</script>

  
</body>

</html>